﻿using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {
	
	private Entity playerEntity;
	private CharacterAnimation characterAnimation;
	private IInputController InputController;
	private Vector2 movement;
	private Vector2 playerFacingDirection = new Vector2(1.0f, 0.0f);

	private Entity thePlayerEntity;
	private Transform currentWeapon;
	private IWeapon currentWeaponComponent;
	private WeaponCollection weaponList;

	// Use this for initialization
	void Start () 
	{
		thePlayerEntity = GetComponent<Entity>();
		InputController = (IInputController)GetComponent(typeof(IInputController));
		characterAnimation = GetComponent<CharacterAnimation>();
		LoadUpWeapon();
	}
	
	// Update is called once per frame
	void Update () 
	{
		DoBasicMovement();

		if (InputController.FireButtonDown())
		{
			currentWeaponComponent.DoWeaponAttack(playerFacingDirection);
		}

		if (InputController.SwapWeaponPressed())
		{
			LoadUpWeapon();
		}
	}

	void FixedUpdate()
	{
		rigidbody2D.velocity = movement;
	}

	private void DoBasicMovement()
	{
		Vector2 theDirectionOfMovement = InputController.GetMovementDirection();
		movement.x = theDirectionOfMovement.x * thePlayerEntity.moveSpeed;
		movement.y = theDirectionOfMovement.y * thePlayerEntity.moveSpeed;

		if (movement.x == 0 && movement.y == 0)
		{
			if (characterAnimation)
				characterAnimation.SetCharacterMoving(false);

			return;
		}

		if (characterAnimation)
		{
			characterAnimation.SetCharacterMoving(true);
			characterAnimation.SetPlayerFacingDirection(movement);
		}
	
		playerFacingDirection = movement;
	}

	void LoadUpWeapon()
	{
		if (currentWeapon)
		{
			currentWeapon.GetComponent<SpriteRenderer>().enabled = false;
		}

		weaponList = GetComponent<WeaponCollection>();

		currentWeapon = Instantiate(weaponList.getNextWeapon(), this.transform.position, new Quaternion()) as Transform;
		currentWeapon.transform.parent = this.transform;
		currentWeapon.localScale = this.transform.localScale/2;


		currentWeaponComponent = (IWeapon)currentWeapon.GetComponent(typeof(IWeapon));
	}
}
